package com.sunhao.demo;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //创建是否被暂停播放了
    private boolean isPaused = false;


    private int musicIndex = 0;


    //获取初始音量，方便恢复
    private int originalVolumn;

    //判断都否设置静音
    private boolean volumnFlag=false;

    private MediaPlayer player;

    private String[] Urls = new String[]{
            "https://dl.stream.qqmusic.qq.com/C400000tGFPi4U6S58.m4a?guid=6861441808&vkey=E67D974FB9AB56AA44A65166950C9EDB9A50FFD6CE12D4B4BF3F60AA34AD74D1CAE4502CC8DD68AECBF5E75B2DBFD44A2759066B9109B06C&uin=2903123788&fromtag=120032",
            "https://dl.stream.qqmusic.qq.com/C400000YVgis395w2o.m4a?guid=1368584328&vkey=225DEEE62791EF22C06E600C74E0EC6BAEC1DC1C7C64B1038CBBA89667FA427B8D57BDD8D9B1C230F5659A5D335C4C403F532313026B3EAB&uin=2903123788&fromtag=120032"};
    private ImageView start;

    private ImageView stop;
    private SeekBar seekBar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        启动按钮
        start = findViewById(R.id.start);
        start.setOnClickListener(this);

//        暂停按钮
        stop = findViewById(R.id.stop);
        stop.setOnClickListener(this);


        //        下一曲按钮
        ImageView next = findViewById(R.id.next);
        next.setOnClickListener(this);


        //        上一曲按钮
        ImageView previous = findViewById(R.id.previous);
        previous.setOnClickListener(this);


        seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //当进度条改变时
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (b) {
                    player.seekTo(i);
                }
            }

            //当用户拖动进度条时
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                player.pause();
            }

            //当用户停止拖动进度条后
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                player.start();
            }
        });

        //初始化音量进度条
        SeekBar volume = findViewById(R.id.volume);

        //获取系统音量
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int currentVolumn = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        volume.setMax(maxVolume);
        volume.setProgress(currentVolumn);

        //控制应用音量大小
        volume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //初始化应用音量
//            private float volume = 0.5f;

            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (b) {
//                    volume = i / 100f;
                    player.setVolume(currentVolumn, currentVolumn);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


        //设置静音效果
         ImageView volumeoff = findViewById(R.id.volumeoff);

         volumeoff.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                 if(volumnFlag){
                     audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,currentVolumn,0);
                 }else {
                     if(audioManager!=null){
                         audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,0,0);
                         volumnFlag=true;
                     }
                 }


             }
         });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start:
//                点击启动按钮后，暂停按钮出现,
                stop.setVisibility(View.VISIBLE);
                start.setVisibility(View.GONE);

                if (isPaused) {
                    player.start();
                    //变成非暂停状态
                    isPaused = false;
                    return;
                }

                //创建媒体播放器,播放第一首歌曲
                player = new MediaPlayer();


                try {
                    player.setDataSource(Urls[musicIndex]);
                    player.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                player.start();


                //开始播放时，更新进度条,设置最大值
                seekBar.setMax(player.getDuration());

                // 创建一个线程，实时更新进度条的进度
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (player != null && player.isPlaying()) {
                            try {
                                Thread.sleep(1000);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 更新进度条的当前进度
                                        seekBar.setProgress(player.getCurrentPosition());
                                    }
                                });
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();


                break;
            case R.id.stop:
                start.setVisibility(View.VISIBLE);
                stop.setVisibility(View.GONE);

                //点击暂停按钮是，暂停播放
                player.pause();
                isPaused = true;
                break;

            case R.id.previous:

                if (musicIndex == 0) {
                    Toast.makeText(this, "没有可播放的上一首音乐", Toast.LENGTH_SHORT).show();
                    return;
                }

                //切换上一首音乐源
                try {
                    player.reset();
                    player.setDataSource(Urls[musicIndex - 1]);
                    player.prepare();
                    player.start();
                    musicIndex--;
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //更新进度条
                seekBar.setMax(player.getDuration());
                seekBar.setProgress(player.getCurrentPosition());
                break;

            case R.id.next:
                if (musicIndex == Urls.length - 1) {
                    Toast.makeText(this, "没有可播放的下一首音乐了", Toast.LENGTH_SHORT).show();
                    return;
                }
                //切换上一首音乐源
                try {
                    player.reset();
                    player.setDataSource(Urls[musicIndex + 1]);
                    player.prepare();
                    player.start();
                    musicIndex++;
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //更新进度条
                seekBar.setMax(player.getDuration());
                seekBar.setProgress(player.getCurrentPosition());
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        player.release();
        //销毁时，释放media资源
    }
}